<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    public $table = 'order';

    protected $fillable = [
    	'id',
        'order_no',
        'pay_status',
        'product_amount_total',
        'total_amount',
        'pay_type',
        'out_trade_no',
        'wechat_id',
        'pay_time',
    ];

    const STATUS_FRESH = 0; // 新订单
    const STATUS_FAIL = 1; // 付款失败
    const STATUS_SUCCESS = 2; // 付款成功
    const STATUS_PAID = 3;//已退款
    // const STATUS_COMPLETE = 10;//未知状态



    public  function user()
    {
    	return $this->hasOne('App\Models\UsersWechat','id','wechat_id');
    }

    public function getTotalAmountHandleAttribute(){
    	return $this->attributes['total_amount'] / 100;
    }



    // 未付款,已付款,已发货,已签收,退货申请,退货中,已退货,取消交易
    public function getPayStatusHandleAttribute(){
    	switch ($this->attributes['pay_status']) {
    		case '0':
    			return '未支付';
    			break;
    		case '1':
    			return '支付失败';
    			break;
    		case '2':
    			return '已付款';
    			break;
			case '3':
    			return '已退款';
    			break;
    		default:
    			return '未知状态';
    			# code...
    			break;
    	}
    }

    public function getPayTypeHandleAttribute(){
        switch ($this->attributes['type']) {
            case 'box':
                return 'scaler box';
                break;
            case 'act':
                return '活动报名';
                break;
            case 'energy':
                return '能量加油';
                break;
            default:
                return '未知类型';
                break;
        }

    }



    /**
     * 创立订单
     */
    public static function add($data = [])
    {
        $order = new Order();
        switch ($data['type']){
            case 'box':
                    $people_number = SiteConfig::where('option_name', 'people_number')->value('option_value');
                    if ($people_number < 2) {//数值为1的时候 就不可购买;
                        return ['return_code' => 'ERROR','msg' => '对不起已没有剩余名额，请关注下次开放'];
                    }
                    $box_price = SiteConfig::where('option_name', 'box_price')->value('option_value');
                    if ($box_price <= 0) {
                        return ['return_code' => 'ERROR','msg' => '订单错误'];
                    }

                    //关怀盒子没有使用完，自己的盒子没有使用完，不能进行第三次续费
                    $orderCount = Order::where('wechat_id',$data['wechat_id'])->where('pay_status',self::STATUS_SUCCESS)->count('id');
                    $Boxcount = Box::where('status','<',6)->count('id');
                    $BoxCareCount = BoxCare::where('status','<',6)->count('id');

                    if ($orderCount>=2 && ($Boxcount > 0 || $BoxCareCount >0)) {
                        return ['return_code' => 'ERROR','msg' => '还有未使用的盒子;不可再次购买'];
                    }
                    $order->order_no = self::createNo('box');//盒子服务
                    $order->product_amount_total = $box_price * 100;
                    $order->type = 'box';
                    $order->name = 'scaler box';
                break;
            case 'act':
                    $row = Activity::with('class')->where('status',1)->find($data['id']);
                    if (!$row) {
                        return ['return_code' => 'ERROR','msg' => '活动不存在'];
                    }
                    if ($row->status==0) {
                        return ['return_code' => 'ERROR','msg' => '活动暂未开启报名'];
                    }
                    if ($row->status==2) {
                        return ['return_code' => 'ERROR','msg' => '活动报名以结束'];
                    }
                    $joinCount = ActivityJoin::where('activity_id',$data['id'])->count('id');
                    if ($row->user_number == $joinCount) {
                        return ['return_code' => 'ERROR','msg' => '报名人数已满'];
                    }

                    $order->order_no = self::createNo('act');//参加活动
                    $order->table_id = $row->id;
                    $order->name = $row->title;
                    $order->product_amount_total = $row->price * 100;
                    $order->type = 'act';
                break;
            case 'energy':
                    if (!array_key_exists('title',$data) || !array_key_exists('price',$data) ) {
                        return ['return_code' => 'ERROR','msg' => '缺少参数'];
                    }
                    //能量补充
                    $row = new EnergyCome;
                    $row->title = $data['title'];
                    $row->price = $data['price'];
                    $row->wechat_id = $data['wechat_id'];
                    $row->status =1;
                    $row->Save();

                    $order->order_no = self::createNo('energy');//能量补充
                    $order->table_id = $row->id;
                    $order->name = $row->title;
                    $order->product_amount_total = $row->price * 100;
                    $order->type = 'energy';
                break;
            default:
                return ['return_code' => 'ERROR','msg' => '订单类型无效'];
            break;
        }
        $order->wechat_id = $data['wechat_id'];
        $order->pay_status = 0;//0待付款
        $order->pay_type = $data['pay_type'];//支付方式
        $order->save();
        return ['return_code' => 'SUCCESS','msg' => 'SUCCESS','data'=>$order];
    }

    //回调情况失败看log文件夹里面的error和pay日志  Handler中处理了;error.log记录
    public static function Handle($data)
    {
        $order = Order::where('order_no', $data['out_trade_no'])->first();
        if (empty($order) || $order->pay_status > 0) { // 如果订单不存在 或者 订单已经支付过了
            return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
        }
        file_put_contents(storage_path('logs/Pay.log') , json_encode($data) .PHP_EOL, FILE_APPEND);
        if ($data['result_code'] === 'SUCCESS') {
            $order->pay_time = date("Y-m-d H:i:s");
            $order->pay_status = self::STATUS_SUCCESS;
            $order->total_amount = $data['cash_fee'];
            $order->save();
            switch ($order->type) {
                case 'box':
                    // 保存订单;
                    $wechat = UsersWechat::find($order->wechat_id);
                    if ($wechat->type==0) {
                        //普通用户转会员
                        UsersWechat::VipCreate($wechat->id,$order->prepay_id);
                    }
                    //生成盒子
                    Box::add($order->id,$order->wechat_id);

                    //生成四个关怀盒子
                    BoxCare::addBoxCare($wechat->id);

                    //进行第三次续费的时候，清除最早的那 6 个盒子和 4 个关怀盒子
                    if (Order::where('wechat_id', $order->wechat_id)->where('pay_status',self::STATUS_SUCCESS)->count('id') > 2) {
                        Box::where('wechat_id',$order->wechat_id)->limit(4)->delete();
                        BoxCare::where('wechat_id',$order->wechat_id)->limit(6)->delete();
                    }

                    if (\DB::table('activity_join_number')->where('wechat_id',$order->wechat_id)->count('id') > 0) {
                        \DB::table('activity_join_number')->where('wechat_id',$order->wechat_id)->increment('number',2);
                    }else{
                        \DB::table('activity_join_number')->where('wechat_id',$order->wechat_id)->insert(['wechat_id'=>$order->wechat_id,'number'=>2]);
                    }

                    break;
                case 'activity':
                    //报名成功
                    $row = new ActivityJoin;
                    $row->wechat_id = $order->wechat_id;
                    $row->activity_id = $order->table_id;
                    $row->price = $order->total_amount;
                    $row->save();
                    \DB::table('activity_join_number')->where('wechat_id',$order->wechat_id)->decrement('number');
                    break;
                case 'energy':
                    //能量加油
                    $row = EnergyCome::find($order->table_id);
                    $row->status = 2;
                    $row->Save();
                    break;
                default:
                    file_put_contents(storage_path('logs/errorPay2.log') , $data['out_trade_no'].'异常类型'.$order->type .PHP_EOL, FILE_APPEND);
                    break;
            }
        }else if($data['result_code'] === 'FAIL'){
            file_put_contents(storage_path('logs/errorPay.log') , json_encode($data) .PHP_EOL, FILE_APPEND);
            file_put_contents(storage_path('logs/errorPay.log') , $data['out_trade_no']."订单异常" .PHP_EOL, FILE_APPEND);
            $order->pay_status = self::STATUS_FAIL;
            $order->save();
        }else{
            return false;
        }
        return true;
    }
    /**
     * @brief 生成订单号
     */
    public static function createNo($type)
    {
        $no = date('Ymd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $type.$no;
    }
}
